import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Input,
  Select,
  Card,
  Modal,
  Form,
  message,
  Popconfirm,
  Tag,
  Avatar,
  Tooltip,
  Row,
  Col,
  Divider,
  Typography,
  Drawer,
  Descriptions,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,
  UserOutlined,
  EyeOutlined,
  KeyOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { User, Role, Department, Team } from '../../types/rbac';
import { useUsers } from '../../hooks/business';

const { Search } = Input;
const { Option } = Select;
const { Title, Text } = Typography;

const Users: React.FC = () => {
  // 使用hooks
  const {
    users,
    loading,
    total,
    availableRoles,
    availableDepartments,
    availableTeams,
    loadUsers,
    createUser,
    updateUser,
    deleteUser,
    batchDeleteUsers,
    resetPassword,
    refresh,
  } = useUsers();



  // 本地状态
  const [searchText, setSearchText] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  
  // 弹窗状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isViewDrawerVisible, setIsViewDrawerVisible] = useState(false);
  const [isPasswordModalVisible, setIsPasswordModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [viewingUser, setViewingUser] = useState<User | null>(null);
  const [resetPasswordUser, setResetPasswordUser] = useState<User | null>(null);

  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();

  // 初始化加载
  useEffect(() => {
    handleSearch();
  }, []);

  // 搜索处理
  const handleSearch = () => {
    const params = {
      keyword: searchText,
      current: currentPage,
      size: pageSize,
    };
    loadUsers(params);
  };

  // 重置搜索条件
  const handleReset = () => {
    setSearchText('');
    setCurrentPage(1);
    loadUsers({ current: 1, size: pageSize });
  };

  // 分页处理
  const handleTableChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    const params = {
      keyword: searchText,
      current: page,
      size,
    };
    loadUsers(params);
  };

  // 新增用户
  const handleAdd = () => {
    setEditingUser(null);
    setIsModalVisible(true);
    form.resetFields();
  };

  // 编辑用户
  const handleEdit = (record: User) => {
    setEditingUser(record);
    setIsModalVisible(true);
    form.setFieldsValue({
      ...record,
      roleIds: record.roles?.map(role => ({ value: role.id, label: role.name })) || [],
      departmentIds: record.departments?.map(dept => ({ value: dept.id, label: dept.name })) || [],
      teamIds: record.teams?.map(team => ({ value: team.id, label: team.name })) || [],
    });
  };

  // 查看用户详情
  const handleView = (record: User) => {
    setViewingUser(record);
    setIsViewDrawerVisible(true);
  };

  // 删除用户
  const handleDelete = async (record: User) => {
    try {
      await deleteUser(record.id);
      message.success('删除成功');
      handleSearch();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的用户');
      return;
    }
    
    try {
      await batchDeleteUsers(selectedRowKeys as string[]);
      message.success('批量删除成功');
      setSelectedRowKeys([]);
      handleSearch();
    } catch (error) {
      message.error('批量删除失败');
    }
  };



  // 权限条件验证函数
  const canEditUser = (user: User): boolean => {
    // 判断当前用户是否有编辑目标用户的权限
    // 1. 超级管理员可以编辑所有用户
    // 2. 部门管理员只能编辑本部门及下级部门的用户
    // 3. 普通用户只能编辑自己
    // 这里可以调用后端的 validatePermissionConditions API
    return true; // 简化处理，实际需要根据权限条件判断
  };

  const canDeleteUser = (user: User): boolean => {
    // 判断是否有删除用户的权限
    // 1. 不能删除自己
    // 2. 不能删除系统管理员
    // 3. 只能删除权限范围内的用户
    return user.status !== 1 || !user.roles?.some(role => role.roleKey === 'admin');
  };

  const canResetPassword = (user: User): boolean => {
    // 判断是否有重置密码的权限
    // 不能重置比自己级别高的用户密码
    return true; // 简化处理
  };

  // 重置密码
  const handleResetPassword = (record: User) => {
    setResetPasswordUser(record);
    setIsPasswordModalVisible(true);
    passwordForm.resetFields();
  };

  // 保存用户
  const handleSave = async (values: any) => {
    try {
      const userData = {
        ...values,
        roles: values.roleIds?.map((item: { value: string; label: string }) => ({ id: item.value, name: item.label })) || [],
        departments: values.departmentIds?.map((item: { value: string; label: string }) => ({ id: item.value, name: item.label })) || [],
        teams: values.teamIds?.map((item: { value: string; label: string }) => ({ id: item.value, name: item.label })) || [],
      };

      if (editingUser) {
        await updateUser({ ...userData, id: editingUser.id });
        message.success('更新成功');
      } else {
        await createUser(userData);
        message.success('创建成功');
      }
      
      setIsModalVisible(false);
      handleSearch();
    } catch (error) {
      message.error(editingUser ? '更新失败' : '创建失败');
    }
  };

  // 确认重置密码
  const handleConfirmResetPassword = async (values: any) => {
    if (!resetPasswordUser) return;
    
    try {
      await resetPassword(resetPasswordUser.id);
      message.success('密码重置成功');
      setIsPasswordModalVisible(false);
    } catch (error) {
      message.error('密码重置失败');
    }
  };

  // 获取状态标签
  const getStatusTag = (status: number) => {
    switch (status) {
      case 1:
        return <Tag color="green">启用</Tag>;
      case 0:
        return <Tag color="red">禁用</Tag>;
      case 2:
        return <Tag color="orange">锁定</Tag>;
      default:
        return <Tag>未知</Tag>;
    }
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      width: 80,
      render: (avatar: string, record: User) => (
        <Avatar
          size={40}
          src={avatar}
          icon={<UserOutlined />}
          alt={record.realName || record.username}
        />
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      width: 150,
      render: (roles: Role[]) => (
        <div>
          {roles?.map(role => (
            <Tag key={role.id} color="blue" style={{ marginBottom: 4 }}>
              {role.name}
            </Tag>
          ))}
        </div>
      ),
    },
    {
      title: '部门',
      dataIndex: 'departments',
      key: 'departments',
      width: 150,
      render: (departments: Department[]) => (
        <div>
          {departments?.map(dept => (
            <Tag key={dept.id} color="purple" style={{ marginBottom: 4 }}>
              {dept.name}
            </Tag>
          ))}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record: User) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              disabled={!canEditUser(record)}
            />
          </Tooltip>
          <Tooltip title="重置密码">
            <Button
              type="text"
              icon={<KeyOutlined />}
              onClick={() => handleResetPassword(record)}
              disabled={!canResetPassword(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
            disabled={!canDeleteUser(record)}
          >
            <Tooltip title={canDeleteUser(record) ? '删除' : '无删除权限'}>
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                disabled={!canDeleteUser(record)}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  return (
    <div>


      {/* 页面标题和操作区域 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <TeamOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            用户管理
          </Title>
          <Text type="secondary">管理系统用户信息和权限分配</Text>
        </div>
        <Space>
          <Search
            placeholder="搜索用户名、姓名、邮箱"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onSearch={handleSearch}
            style={{ width: 300 }}
            allowClear
          />
          <Button icon={<ReloadOutlined />} onClick={refresh}>
            刷新
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增用户
          </Button>
        </Space>
      </div>

      <Card bodyStyle={{ padding: 0 }}>
        {/* 筛选区域 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '24px 24px 0 24px' }}>
          <div>
            <Text type="secondary">
              共 {total || 0} 个用户
              {selectedRowKeys.length > 0 && `，已选择 ${selectedRowKeys.length} 个`}
            </Text>
          </div>
        </div>
        
        <div style={{ padding: '0 24px 24px 24px' }}>

          {/* 用户表格 */}
          <Table
            columns={columns}
            dataSource={users}
            rowKey="id"
            loading={loading}
            rowSelection={rowSelection}
            scroll={{ x: 1200 }}
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) =>
                `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
              onChange: handleTableChange,
              onShowSizeChange: handleTableChange,
            }}
          />
        </div>
      </Card>

      {/* 新增/编辑用户弹窗 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="realName"
                label="真实姓名"
                rules={[{ required: true, message: '请输入真实姓名' }]}
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入真实姓名" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="phone"
                label="手机号"
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            {!editingUser && (
              <Col span={8}>
                <Form.Item
                  name="password"
                  label="密码"
                  rules={[{ required: true, message: '请输入密码' }]}
                  style={{ marginBottom: 16 }}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </Col>
            )}
            <Col span={8}>
              <Form.Item
                name="status"
                label="状态"
                initialValue={1}
                style={{ marginBottom: 16 }}
              >
                <Select>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                  <Option value={2}>锁定</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="roleIds"
                label="角色"
                style={{ marginBottom: 16 }}
              >
                <Select
                  mode="multiple"
                  placeholder="请选择角色"
                  allowClear
                  labelInValue
                >
                  {availableRoles.map(role => (
                    <Option key={role.id} value={role.id}>
                      {role.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="departmentIds"
                label="部门"
                style={{ marginBottom: 16 }}
              >
                <Select
                  mode="multiple"
                  placeholder="请选择部门"
                  allowClear
                  labelInValue
                >
                  {availableDepartments.map(dept => (
                    <Option key={dept.id} value={dept.id}>
                      {dept.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="teamIds"
                label="团队"
                style={{ marginBottom: 16 }}
              >
                <Select
                  mode="multiple"
                  placeholder="请选择团队"
                  allowClear
                  labelInValue
                >
                  {availableTeams.map(team => (
                    <Option key={team.id} value={team.id}>
                      {team.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="描述"
            style={{ marginBottom: 16 }}
          >
            <Input.TextArea rows={2} placeholder="请输入描述" />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingUser ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看用户详情侧边栏 */}
      <Drawer
        title={
          <Space>
            <EyeOutlined style={{ color: '#1890ff' }} />
            <span>用户详情</span>
          </Space>
        }
        open={isViewDrawerVisible}
        onClose={() => setIsViewDrawerVisible(false)}
        width={600}
        extra={
          <Button 
            type="primary" 
            icon={<EditOutlined />}
            onClick={() => {
              setIsViewDrawerVisible(false);
              if (viewingUser) {
                handleEdit(viewingUser);
              }
            }}
          >
            编辑
          </Button>
        }
      >
        {viewingUser && (
          <div>
            {/* 用户头部信息 */}
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <div style={{
                width: 80,
                height: 80,
                borderRadius: '50%',
                backgroundColor: '#1890ff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: 'white',
                fontSize: '28px',
                fontWeight: 'bold',
                margin: '0 auto 16px'
              }}>
                {viewingUser.avatar ? (
                  <Avatar size={80} src={viewingUser.avatar} />
                ) : (
                  (viewingUser.realName || viewingUser.username).charAt(0)
                )}
              </div>
              <div>
                <Title level={4} style={{ margin: 0, color: '#262626' }}>
                  {viewingUser.realName || viewingUser.username}
                </Title>
                <Text type="secondary" style={{ fontSize: 14 }}>
                  用户名: {viewingUser.username}
                </Text>
              </div>
              <div style={{ marginTop: 12 }}>
                {getStatusTag(viewingUser.status)}
              </div>
            </div>

            <Divider />

            {/* 基本信息 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <UserOutlined style={{ marginRight: 8 }} />
              基本信息
            </Title>
            <Descriptions bordered column={1} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="用户名">{viewingUser.username}</Descriptions.Item>
              <Descriptions.Item label="真实姓名">{viewingUser.realName || '-'}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{viewingUser.email || '-'}</Descriptions.Item>
              <Descriptions.Item label="手机号">{viewingUser.phone || '-'}</Descriptions.Item>
              <Descriptions.Item label="状态">
                {getStatusTag(viewingUser.status)}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {viewingUser.createTime ? new Date(viewingUser.createTime).toLocaleString() : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {viewingUser.updateTime ? new Date(viewingUser.updateTime).toLocaleString() : '-'}
              </Descriptions.Item>
              {viewingUser.description && (
                <Descriptions.Item label="描述">
                  {viewingUser.description}
                </Descriptions.Item>
              )}
            </Descriptions>

            {/* 角色权限信息 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <TeamOutlined style={{ marginRight: 8 }} />
              角色权限
            </Title>
            <div style={{ 
              padding: '16px', 
              backgroundColor: '#fafafa', 
              borderRadius: 8,
              border: '1px solid #f0f0f0',
              marginBottom: 24
            }}>
              <Row gutter={16}>
                <Col span={8}>
                  <div style={{ marginBottom: 12 }}>
                    <Text strong>角色</Text>
                  </div>
                  <div>
                    {viewingUser.roles && viewingUser.roles.length > 0 ? (
                      viewingUser.roles.map(role => (
                        <Tag key={role.id} color="blue" style={{ marginBottom: 4 }}>
                          {role.name}
                        </Tag>
                      ))
                    ) : (
                      <Text type="secondary">暂无角色</Text>
                    )}
                  </div>
                </Col>
                <Col span={8}>
                  <div style={{ marginBottom: 12 }}>
                    <Text strong>部门</Text>
                  </div>
                  <div>
                    {viewingUser.departments && viewingUser.departments.length > 0 ? (
                      viewingUser.departments.map(dept => (
                        <Tag key={dept.id} color="purple" style={{ marginBottom: 4 }}>
                          {dept.name}
                        </Tag>
                      ))
                    ) : (
                      <Text type="secondary">暂无部门</Text>
                    )}
                  </div>
                </Col>
                <Col span={8}>
                  <div style={{ marginBottom: 12 }}>
                    <Text strong>团队</Text>
                  </div>
                  <div>
                    {viewingUser.teams && viewingUser.teams.length > 0 ? (
                      viewingUser.teams.map(team => (
                        <Tag key={team.id} color="orange" style={{ marginBottom: 4 }}>
                          {team.name}
                        </Tag>
                      ))
                    ) : (
                      <Text type="secondary">暂无团队</Text>
                    )}
                  </div>
                </Col>
              </Row>
            </div>
          </div>
        )}
      </Drawer>

      {/* 重置密码弹窗 */}
      <Modal
        title="重置密码"
        open={isPasswordModalVisible}
        onCancel={() => setIsPasswordModalVisible(false)}
        footer={null}
        width={400}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handleConfirmResetPassword}
        >
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请确认密码" />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setIsPasswordModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Users;